<?php

class Ext_Music_Save
{
    public function __construct()
    {
    }
    
    public function save($datas)
    {
        $result = array(
            'code'     => Ext_Music_Save_Result::FAILURE,
            'data'     => '',
            'messages' => array(),
        );

        $musicRow = App_Model_DbTable_Music::getInstance()->getRowByHostViewId($datas['host'], $datas['viewId']);
        if(isset($musicRow['id'])){
            $result['code'] = Ext_Music_Save_Result::SUCCESS;
            $result['data'] = $musicRow['id'];
            return new Ext_Music_Save_Result($result['code'], $result['data'], $result['messages']);
        }
        
        $downloader = new Ext_Image_Download($datas['photo']);
        $downloadResulter = $downloader->download();
        if(!$downloadResulter->isValid())
        {
            $result['messages'] = $downloadResulter->getMessages();
            return new Ext_Music_Save_Result($result['code'], $result['data'], $result['messages']);
        }
        $imageFile = $downloadResulter->getData();
        
        $saver = new Ext_Image_Save();
        $saveResultor = $saver->save($imageFile);
        if(!$saveResultor->isValid()){
            $result['messages'] = $saveResultor->getMessages();
            return new Ext_Video_Save_Result($result['code'], $result['data'], $result['messages']);
        }
        $imageId = $saveResultor->getData();
        
        $row = array(
            'host'               => $datas['host'],
            'viewId'             => $datas['viewId'],
            'url'                => $datas['url'],
            'imageId'            => $imageId,
            'createTime'         => time(),
        );
        $musicId = App_Model_DbTable_Music::getInstance()->addNew($row);
        
        $result['code'] = Ext_Music_Save_Result::SUCCESS;
        $result['data'] = $musicId;
        return new Ext_Music_Save_Result($result['code'], $result['data'], $result['messages']);
    }
    
}
